package org.hepeng.workx.util.serializer;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;

import java.io.ByteArrayInputStream;

/**
 * https://github.com/EsotericSoftware/kryo/
 * @author he peng
 */
public class KryoObjectSerializer<T> extends ExceptionTranslationObjectSerializer<T> {

    private static final KryoPool KRYO_POOL = new KryoPool.Builder(new KryoFactoryImpl()).build();

    @Override
    protected byte[] convert(T object) throws Exception {
        Kryo kryo = KRYO_POOL.borrow();
        Output output = new Output(1024);
        kryo.writeObject(output , object);
        byte[] bytes = output.toBytes();
        output.close();
        KRYO_POOL.release(kryo);
        return bytes;
    }

    @Override
    protected T convert(byte[] bytes) throws Exception {
        Kryo kryo = KRYO_POOL.borrow();
        Input input = new Input(new ByteArrayInputStream(bytes));
        T t = kryo.readObject(input, this.serializationClass);
        input.close();
        KRYO_POOL.release(kryo);
        return t;
    }
}
